/**
 * Created by liubin on 2017/4/26.
 */



var DzpkTableLayer = GameCCSBase.extend({

    mDzpkCardLayer : null,
    mDzpkUILayer : null,
    mDzpkOprationLayer : null,
    mDzpkTableSettingLayer : null,
    mKwxApplyTableLayer : null,
    mDzpkTableChatLayer : null,
    mDzpkTableChatInfoLayer : null,
    mDzpkCardTypeTipLayer : null,
    mDzpkTableRoomEndLayer : null,
    mDzpkTableEndLayer : null,
    mDzpkTableReplayLayer : null,
    mDzpkTableMicLayer : null,
    mDzpkTablePlayerInfoLayer : null,

    //是否是创建者
    mIsRoomCreator : null,

    //记录当前局本地打了几盘了
    mPlayGameCount : null,

    //包房id 通过退出牌桌消息获得
    mGroupId : null,

    Text_roomInfo : null,

    mPlayerType : null,


    //结算消息（特殊处理）
    mDzpkRoundEndedEventdzpk : null,

    ctor : function(){
        this._super();
        this.loadCocostudio("res/ccs/DzpkTable.json");

        mo.dzpkTable = this;
        this.mIsRoomCreator = false;

        this.loadUI();
    },

    onEnter : function(){
        this._super();
        mo.soundHelper.stopMusic();
        mo.eventHelper.add("DzpkForceExitTableResponsedzpkOK", this, function () {
            if (mo.dzpkTableStatus.mTableStatus.LeftPlayTimes == mo.dzpkTable.mGameConfig.maxpan){
                mo.showMsgDialogOk("退出牌局成功", function(){
                    this.quitDzpkGame();
                }, this);
            }
        });

        mo.eventHelper.add("CancleJuRequestdzpk", this, function(cancleJu){
            this.mKwxApplyTableLayer.updateCancelJuInfo(cancleJu);
        });

        mo.eventHelper.add("UserChatMsgResponse", this, function(userChatMsgResponse){
            this.mDzpkTableChatInfoLayer.setChatMsg(userChatMsgResponse);
        });
    },

    onExit : function () {
        this.unschedule(this.refreshLeftTime);
        mo.eventHelper.remove(this);
        this._super();
    },

    loadUI : function () {
        mo.dzpkCardHelper.init();

        cc.spriteFrameCache.addSpriteFrames("res/dzpkCards.plist", "res/dzpkCards.png");
        cc.spriteFrameCache.addSpriteFrames("res/emojis.plist", "res/emojis.png");
        cc.spriteFrameCache.addSpriteFrames("res/emojis_index.plist", "res/emojis_index.png");

        this.mDzpkUILayer = new DzpkTableUILayer();
        this.addChild(this.mDzpkUILayer);

        this.mDzpkCardLayer = new DzpkCardLayer();
        this.addChild(this.mDzpkCardLayer);

        //个人信息
        this.mDzpkTablePlayerInfoLayer = new KwxTablePlayerInfoLayer();
        this.addChild(this.mDzpkTablePlayerInfoLayer);

        //语音
        if (cc.sys.isNative){
            this.mDzpkTableMicLayer = new DzpkTableMicLayer();
            this.addChild(this.mDzpkTableMicLayer);
        }

        //操作
        this.mDzpkOprationLayer = new DzpkOprationLayer();
        this.addChild(this.mDzpkOprationLayer);

        //设置
        this.mDzpkTableSettingLayer = new KwxDialogSetting("dzpk");
        this.addChild(this.mDzpkTableSettingLayer);

        //聊天窗口
        this.mDzpkTableChatLayer = new KwxDialogChat();
        this.mDzpkTableChatLayer.setChatButton(mo.seekWidgetByName(this.mDzpkUILayer.ccsNode, "Button_chat"), "dzpk");
        this.addChild(this.mDzpkTableChatLayer);

        //聊天信息
        this.mDzpkTableChatInfoLayer = new DzpkTableChatInfoLayer();
        this.addChild(this.mDzpkTableChatInfoLayer);

        this.mDzpkCardTypeTipLayer = new DzpkCardTypeTipLayer();
        this.addChild(this.mDzpkCardTypeTipLayer);

        this.mDzpkTableEndLayer = new DzpkTableEndLayer();
        this.addChild(this.mDzpkTableEndLayer);

        //取消
        this.mKwxApplyTableLayer = new KwxApplyTableLayer("dzpk");
        this.addChild(this.mKwxApplyTableLayer);

        //录像层
        this.mDzpkTableReplayLayer = new DzpkTableReplayLayer();
        this.addChild(this.mDzpkTableReplayLayer);

        this.Text_roomInfo = mo.seekWidgetByName(this.ccsNode, "Text_roomInfo");

    },

    //正常打牌
    loadPlayCard : function(){
        this.mPlayGameCount = 0;
        this.mPlayerType = 1;

        this.mDzpkUILayer.panel_ready.setVisible(false);

        //隐藏录像界面
        this.mDzpkTableReplayLayer.setVisible(false);

        //隐藏录像时候的ui
        this.mDzpkUILayer.setIsReplay(false);

        if (this.mDzpkTableMicLayer != null){
            this.mDzpkTableMicLayer.setVisible(true);
        }
    },

    //播放录像
    loadReplay : function(rePlaydzpk, replayId){
        this.mPlayGameCount = 0;
        this.mPlayerType = 0;

        this.mDzpkUILayer.panel_ready.setVisible(false);

        //录像规则
        mo.dzpkTable.setDzpkConfig(rePlaydzpk.Result.CfgJson, "", "");

        //打开录像界面 并且播放
        this.mDzpkTableReplayLayer.setVisible(true);
        this.mDzpkTableReplayLayer.setReplayId(replayId);
        this.mDzpkTableReplayLayer.onStart();

        //隐藏录像时候的ui
        this.mDzpkUILayer.setIsReplay(true);

        if (this.mDzpkTableMicLayer != null){
            this.mDzpkTableMicLayer.setVisible(false);
        }

        this.mReplayId = replayId;
        mo.dzpkTableStatus.setReplayMsg(rePlaydzpk);
        mo.dzpkTableStatus.playReplay();
    },

    setDzpkConfig : function(Cfgjson, tablePassWord, GroupName){
        this.mGroupName = GroupName;
        this.mTableEnterPwd = tablePassWord;
        this.mGameConfig = JSON.parse(Cfgjson);
        //密码
        if (mo.gameHelper.developerVersion == "3.0"){

            mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_textRoomId"), "密码：");
            mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_roomId"), "" + tablePassWord);
        }
    },

    //大结算
    onShowJuEndedLayer : function(juEndedEventdzpk){
        //判断是否需要直接退出 如果剩余局数和设置里面的局数一致 就直接退出
        var ruleJson = JSON.parse(juEndedEventdzpk.CfgJson);

        if (mo.dzpkTableStatus.mTableStatus.LeftPlayTimes == ruleJson.maxpan){
            mo.showMsgDialogOk("牌局已经解散", function(){
                this.quitDzpkGame();
            }, this);
        }else{
            this.mDzpkTableRoomEndLayer = new DzpkTableRoomEnd();
            mo.sceneHelper.showEndInfoLayer(this.mDzpkTableRoomEndLayer);
            // this.addChild(this.mDzpkTableRoomEndLayer);
            this.mDzpkTableRoomEndLayer.setRoomEndInfo(juEndedEventdzpk);

            if (juEndedEventdzpk.EndFlag == 0){
                //自然结束 通过当局结算打开
                this.mDzpkTableRoomEndLayer.setVisible(false);
            }else{
                this.mDzpkTableRoomEndLayer.setVisible(true);
            }
        }
    },

    reset : function () {
        this.mDzpkCardLayer.reset();
        this.mDzpkUILayer.reset();
        this.mDzpkOprationLayer.reset();
    },

    fapai : function(seats, coins, cardNums, cardTypes){
        this.mDzpkCardLayer.fapai(seats, cardNums, cardTypes);

        for (var i=0; i<5; i++){
            var PayMoney = coins[i];
            if(PayMoney != 0 && PayMoney != null){
                this.betChip(-1, i, PayMoney, 0);
            }
        }
    },

    betChip : function (code, seat, thisPayMomey, oldPayMomey) {
        this.mDzpkCardLayer.betChip(code, seat, thisPayMomey, oldPayMomey);
    },

    showPublicCards : function (step, TableCards) {
        this.mDzpkCardLayer.showPublicCards(step, TableCards);
    },

    betRoundFinish : function (round) {

        this.runAction(cc.sequence(
            cc.delayTime(1.0),  //最后一个人下筹码
            cc.callFunc(function () {
                //形成筹码池
                this.mDzpkCardLayer.chipToPot(mo.dzpkTableStatus.mTableStatus.Pot);

                //清空当前押注筹码
                for (var i=0; i<5; i++){
                    this.mDzpkUILayer.setBetChipNum(i, 0);

                    var logicSeat = mo.dzpkTableStatus.getLogicForView(i, mo.dzpkTableStatus.mTableStatus.MySeat - 1);
                    var seatuser = mo.dzpkTableStatus.mTableStatus["SeatUser" + (logicSeat + 1)];
                    if(seatuser != null){
                        this.mDzpkUILayer.showActionTip(-1, i, seatuser.State);
                    }

                }
            }, this),
            cc.delayTime(1.0),

            cc.callFunc(function () {
                //显示公牌
                this.showPublicCards(round, mo.dzpkTableStatus.mTableStatus.TableCards);
            }, this),
            cc.delayTime(1.0),
            cc.callFunc(function () {
                //显示牌型
                var seatuser = mo.dzpkTableStatus.mTableStatus["SeatUser" + mo.dzpkTableStatus.mTableStatus.MySeat];
                var cardType = seatuser.Cardtype;
                this.mDzpkUILayer.setCardTypeTextOfSeat(cardType, 0);

                var MaxCards = seatuser.MaxCards;
                this.mDzpkCardLayer.showMaxCardType(MaxCards, cardType);
            }, this)
        ));
    },

    updateTableStep : function (step) {
        //准备界面
        this.mDzpkUILayer.showReady(step == 0);

        var roomInfo = "房间号：" + mo.dzpkTableStatus.mTableStatus.TableID + "\n";
        roomInfo += "大盲注：" + mo.dzpkTableStatus.mTableStatus.BasePoint + "\n";
        roomInfo += "闷" + this.mGameConfig.men + "轮" + "\n";
        roomInfo += "剩余" + mo.dzpkTableStatus.mTableStatus.LeftPlayTimes + "局";

        mo.gameHelper.setTextString(this.Text_roomInfo, roomInfo);
    },


    setCurrentPlayer : function (seat) {
        this.mDzpkUILayer.setCurrentPlayer(seat);
    },


    //显示代开房人
    setShowRoomCreate : function(user){
        if (user != null){
            var kwxDaikaifangWidget = new KwxDaikaifangWidget();
            kwxDaikaifangWidget.setUserInfo(user);
            this.addChild(kwxDaikaifangWidget);
            kwxDaikaifangWidget.setPosition(cc.p(105, mo.gameSize.y - 10));
        }
    },

    quitDzpkGame : function(){
        if (mo.gameHelper.developerVersion == "2.0"){
            mo.sceneHelper.runSceneHall();
        }else if (mo.gameHelper.developerVersion == "3.0"){
            mo.sceneHelper.exitGameLayer();
            if (this.mGroupId != null){
                mo.hallLayer.intoGroup(this.mGroupId);
            }
        }
    },

    setJuesaunInfo : function (dzpkRoundEndedEventdzpk) {
        this.mDzpkRoundEndedEventdzpk = dzpkRoundEndedEventdzpk;

        this.handlerJuesaunInfo(mo.dzpkTableStatus.mTableStatus);
    },

    //触发结算消息
    handlerJuesaunInfo : function(tableStatus) {
        if (this.mDzpkRoundEndedEventdzpk != null) {
            var endInfo = this.mDzpkRoundEndedEventdzpk;
            this.mDzpkRoundEndedEventdzpk = null;

            //筹码池
            var pots = endInfo.Pot;

            var cardTypes = [null, null, null, null, null];

            var cardNumss = [null, null, null, null, null];

            var publicCardNums = [];

            var qipaiFlag = 0; //未弃牌人数

            for (var i = 0; i < 5; i++) {
                var logicSeat = mo.dzpkTableStatus.getLogicForView(i, endInfo.MySeat - 1);
                var seatUser = endInfo["SeatUser" + (logicSeat + 1)];
                if (seatUser != null){
                    cardNumss[i] = seatUser.HandCards;
                    cardTypes[i] = seatUser.Cardtype;

                    if(seatUser.playState == false){
                        cardTypes[i] = 10; //弃牌
                    }else{
                        qipaiFlag ++;
                    }


                    if(logicSeat + 1 == endInfo.MySeat){
                        if(seatUser.HandCards.length == 7){
                            for (var index=0; index<5; index++){
                                publicCardNums.push(seatUser.HandCards[index+2]);
                            }
                        }
                    }
                }
            }

            var round = tableStatus.Round;
            if(round == 1 && qipaiFlag == 1){
                this.mDzpkCardLayer.chipToPot(pots);
                for (var i=0; i<5; i++){
                    this.mDzpkUILayer.setBetChipNum(i, 0);
                    this.mDzpkUILayer.showActionTip(-1, i);
                }
                this.mDzpkTableEndLayer.setEndInfo(endInfo, 2);
            }else{
                this.jiesuan(endInfo, pots, cardNumss, cardTypes, publicCardNums);
            }
        }
    },

    jiesuan : function (endInfo, pots, handleCards, cardTypes, publicCardNums) {

        var delayTime = 1.0;

        this.runAction(cc.sequence(
            cc.delayTime(delayTime), //等上一轮下的筹码飞到位置
            cc.callFunc(function () {
                //形成最终筹码池
                this.mDzpkCardLayer.chipToPot(pots);
                //清空当前押注筹码
                for (var i=0; i<5; i++){
                    this.mDzpkUILayer.setBetChipNum(i, 0);
                    this.mDzpkUILayer.showActionTip(-1, i);
                }
                delayTime = 0.5;
            }, this),
            cc.delayTime(delayTime),  //等筹码飞到筹码池的位置
            cc.callFunc(function () {
                //显示剩余公牌
                this.mDzpkCardLayer.showPublicCardsByCards(publicCardNums);
            }, this),

            cc.delayTime(1.5 * (4 - this.mDzpkCardLayer.mPublicCardStep)),  //等显示所有公牌
            cc.callFunc(function () {
                var seatuser = endInfo["SeatUser" + mo.dzpkTableStatus.mTableStatus.MySeat];
                if(seatuser != null){
                    var MaxCards = seatuser.MaxCards;
                    var cardType = seatuser.Cardtype;
                    this.mDzpkCardLayer.showMaxCardType(MaxCards, cardType);
                }
                //显示所有玩家手牌
                this.mDzpkCardLayer.fanpai(handleCards, cardTypes);
                //结算界面
                this.mDzpkTableEndLayer.setEndInfo(endInfo, 2);
            }, this)
        ));
    },


    setLastRoundInfo : function (roundEndedEventdzpk) {
        this.mDzpkCardTypeTipLayer.setLastRoundInfo(roundEndedEventdzpk);
    },


    //邀请玩家
    onInvite : function(){
        var gameName = "dzpk";
        var configSummary = mo.gameHelper.getRuleConfigSummary(this.mGameConfig, gameName);
        configSummary += "，就等你来了(点击加入)";
        var tableId = mo.dzpkTableStatus.mTableStatus.TableID;

        var title = "桌号:[" + tableId + "]" + "-" + mo.gameHelper.projectName + "-德州扑克";
        var description = configSummary;
        mo.gameHelper.onWxShareWeb(title, description, mo.gameUserInfo.getExternalUrl(1, tableId));
    },

    //分享录像
    onShareReplay : function(){
        var gameName = "dzpk";
        var configSummary = mo.gameHelper.getRuleConfigSummary(this.mGameConfig, gameName);
        configSummary += "，在游戏中输入录像id就能看到我的精彩回放了";

        var title = "录像id:" + this.mReplayId.substr(7) + "-" + mo.gameHelper.projectName + "-德州扑克";
        var description = configSummary;

        mo.gameHelper.onWxShareWeb(title, description, mo.gameUserInfo.getExternalUrl(2, this.mReplayId.substr(7)));
    },

});